package job.manager.db.dao;

import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import job.manager.db.ec.AddressEB;

/**
 *  DAO class is responsible for communcation with the
 *  database regarding addresses.
 */
public class AddressDAO {

    private EntityManager em;

    public AddressDAO() {

    }

    public AddressDAO(EntityManager em) {
        this.em = em;
    }

    public AddressEB getAddress(Integer pk) {
        return em.find(AddressEB.class, pk);
    }

    public Collection<AddressEB> getAddressByPid(Integer pk) {
        Query q = em.createNamedQuery("AddressEB.findByPid");
        q.setParameter("proId", pk);
        return q.getResultList();
    }

    public AddressEB insert(AddressEB address){
        if(address != null){
            em.persist(address);
            em.flush();
            return address;
        }
        return null;
    }


    public int update(AddressEB address){
        if( address != null){
            AddressEB a = em.merge(address);
            em.flush();
            return 1;
        }
        return 0;
    }


    public int delete(AddressEB address){
        if(address != null){
            AddressEB a = em.merge(address);
            em.remove(a);
            return 1;
        }
        return 0;
    }

    public int delete(Integer pk){
        if(pk != null){
            return this.delete(em.find(AddressEB.class, pk));
        }
        return 0;
    }

    public Collection<AddressEB> getAllAddresses(){
        Query q = em.createNamedQuery("AddressEB.findAll");
        return q.getResultList();
    }

}
